/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbDgram.cpp			*/
/********************************************************/

#include "GlbDgram.h"

namespace GlbNet
{

CGlbDgram::CGlbDgram()
{
	memset(&m_stAddr, '\0', sizeof(struct sockaddr_un));
}

CGlbDgram::~CGlbDgram()
{
}

void* CGlbDgram::GlbDgramGetAddr()
{
	return (void*)&m_stAddr;
}

void CGlbDgram::GlbDgramReset()
{
	memset(&m_stAddr, '\0', sizeof(struct sockaddr_un));

	return;
}

void CGlbDgram::GlbDgramSetAddr(void* pAddr)
{
	memcpy(&m_stAddr, pAddr, sizeof(struct sockaddr_un));

	return;
}

void CGlbDgram::GlbDgramSetAddr(char* pszUrl)
{
	memcpy(m_stAddr.sun_path, pszUrl, strlen(pszUrl));
	m_stAddr.sun_family = GLB_AF_UNIX;

	return;
}

int CGlbDgram::GlbDgramConnect()
{
	int iReturn = GLB_SUCCESS;

	if (GLB_SUCCESS == CGlbNet::GlbNetOpen(GLB_AF_UNIX, GLB_SOCK_DGRAM)) {
		CGlbNet::GlbNetSetTimeOut(GLB_TIMEOUT, 0);
		if (connect(CGlbNet::m_iSocket, (struct sockaddr*)&m_stAddr, sizeof(struct sockaddr_un)) < 0) {
			GLB_ERROR("%s\n", strerror(errno));
			iReturn = GLB_FAILURE;
			CGlbNet::GlbNetClose();
		}
	}
	else {
		iReturn = GLB_FAILURE;
	}

	return iReturn;
}

int CGlbDgram::GlbDgramConnect(char* pszUrl)
{
	GlbDgramSetAddr(pszUrl);

	return GlbDgramConnect();
}

int CGlbDgram::GlbDgramConnect(struct sockaddr_un* pstAddr)
{
	GlbDgramSetAddr(pstAddr);

	return GlbDgramConnect();
}

int CGlbDgram::GlbNetInitSend(char* pszUrl)
{
	return GlbDgramConnect(pszUrl);
}

int CGlbDgram::GlbNetInitSend(struct sockaddr_un* pstAddr)
{
	return GlbDgramConnect(pstAddr);
}

int CGlbDgram::GlbDgramOpenBind()
{
	int iReturn = GLB_SUCCESS;

	if (GLB_SUCCESS == CGlbNet::GlbNetOpen(GLB_AF_UNIX, GLB_SOCK_DGRAM)) {
		if (GLB_SUCCESS != GlbNetBind(&m_stAddr)) {
			GLB_ERROR("%s\n", strerror(errno));
			CGlbNet::GlbNetClose();
			return GLB_FAILURE;
		}
	}
	else {
		iReturn = GLB_FAILURE;
	}

	return iReturn;
}

int CGlbDgram::GlbNetInitRecv(char* pszUrl)
{
	GlbDgramSetAddr(pszUrl);

	return GlbDgramOpenBind();
}

int CGlbDgram::GlbNetInitRecv(struct sockaddr_un* pstAddr)
{
	GlbDgramSetAddr(pstAddr);

	return GlbDgramOpenBind();
}

} /* GlbNet */
